﻿using Basic.RateLimit.Handler;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;

namespace Basic.RateLimit.Middleware
{

    /// <summary>
    /// 限流中间件
    /// </summary>
    public class RateLimitMiddleware : IMiddleware
    {
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            RateLimitFactory factory = context.RequestServices.GetService<RateLimitFactory>();
            string path = context.Request.Path;
            string group = context.Request.Headers.TryGetValue("RateLimitGroup", out var key) ? key.ToString() : null;
            if (factory.CheckRateLimit(path, group))
            {
                await next.Invoke(context);
            }
            else
            {
                context.Response.StatusCode = 429;
                await context.Response.WriteAsync(ResponseTxt429);
            }
        }

        private static string ResponseTxt429 = "{\"status\":429,\"success\":false}";
    }
}